package com.huangliusong.web.method.suport;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Properties;

/**
 * @author huangliusong
 * @since 2018/10/5
 * {@link HandlerMethodArgumentResolver}
 */
public class PropertiesHandlerMerhodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return Properties.class.equals(parameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

        //
        ServletWebRequest servletWebRequest=(ServletWebRequest)webRequest;
        HttpServletRequest request=((ServletWebRequest)webRequest).getRequest();


        String contengType=request.getHeader("Content-Type");
        MediaType mediaType=MediaType.parseMediaType(contengType);

        //获取字符编码
        Charset charset =mediaType.getCharset();
        //不存在时
        charset=charset==null?Charset.forName("UTF-8"):charset;

        InputStream inputStream=request.getInputStream();
        //　字节流
        InputStreamReader reader=new InputStreamReader(inputStream,charset);

        Properties properties=new Properties();
        //加载字符流　
        properties.load(reader);
        return properties;
    }
}
